package com.putao.album.photodetail;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.dialog.ConfirmDialogBuilder;
import com.putao.album.dialog.PhotoTagManagerDialog;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.fileupload.FileInfo;
import com.putao.album.fileupload.FileUploadDBHelper;
import com.putao.album.photodetail.bean.PhotoViewItem;
import com.putao.album.popupwindow.PtThirdSharePopupWindow;
import com.putao.album.share.ShareTools;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.putao.album.widget.pttag.PtTag;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-5-6.
 * 点击一张相册照片详情界面(包括点赞，亲一下，标签显示)
 */
public class ActivityPhotoDetail extends BaseActivity implements ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private ImageView colletion, tips_kiss, kiss_effect;
    //    private TextView relation;
    private ArrayList<String> photoIds = new ArrayList<String>();
    private int curPhotoPosition;
    //    private PtTagListView tag_view;
//    private final List<PtTag> mTags = new ArrayList<PtTag>();
    private TextView kiss_num;
    private static String ADD_TAG_BTN_TEXT = "添加...";
    private PopupWindow mPopupWindow;
    private ArrayList<PhotoViewFragment> fragments = new ArrayList<PhotoViewFragment>();
    private PhotoViewFragmentAdapter mFragmentAdapter;
    private TextView tag_tv;
    private Dialog moreDialog;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_photo_detail;
    }

    @Override
    public void doInitSubViews(View view) {
        colletion = (ImageView) findViewById(R.id.colletion);
        tips_kiss = (ImageView) findViewById(R.id.tips_kiss);
        kiss_num = (TextView) findViewById(R.id.kiss_num);
        kiss_effect = (ImageView) findViewById(R.id.kiss_effect);

//        relation = (TextView) findViewById(R.id.relation);

        mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
        tag_tv = (TextView) findViewById(R.id.tag_tv);

//        tag_view = (PtTagListView) findViewById(R.id.tag_view);
//        tag_view.setTagViewBackgroundRes(R.drawable.tag_black_half_transparent);

        addOnClickListener(R.id.back_btn, R.id.kiss_layout, R.id.colletion_layout, R.id.tag_layout, R.id.share, R.id.btn_delete, R.id.save, R.id.more_layout);

//        tag_view.setOnTagClickListener(new PtTagListView.OnTagClickListener() {
//            @Override
//            public void onTagClick(PtTagView tagView, PtTag tag) {
//
//                if (ADD_TAG_BTN_TEXT.equals(tag.getTitle())) {
//                    showTagManagerDialog();
//                }
//            }
//        });

    }

    @Override
    public void doInitData() {
        Bundle bundle = getIntent().getExtras();
        photoIds = bundle.getStringArrayList("ids");
        curPhotoPosition = bundle.getInt("position");

        initViewPagerFragment();
    }

    private void initViewPagerFragment() {
        for (int i = 0; i < photoIds.size(); i++) {
            PhotoViewFragment fragment = new PhotoViewFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("index", i);
            bundle.putString("photoId", photoIds.get(i));
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        mFragmentAdapter = new PhotoViewFragmentAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(mFragmentAdapter);
        mViewPager.setOnPageChangeListener(this);
        mViewPager.setCurrentItem(curPhotoPosition);
    }

    public void queryShare(final View v) {
        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("baby_id", CommonUtils.getBabyId());

        params.put("photo_id", item.getPhoto_id());

        final String url = item.getPhoto();

        HttpRequestUtil.doHttpGetRequest(mActivity, PuTaoConstants.API_GET_SHARE_CONTENT,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            JSONObject data = json.getJSONObject("data");
                            String title = data.getString("title");

                            //String url = items.get(mViewPager.getCurrentItem()).getPhoto();
                            mPopupWindow = PtThirdSharePopupWindow.Create(mActivity, url, title, PtThirdSharePopupWindow.SHARE_PHOTO);
                            mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.colletion_layout:
                addCollection();
                break;
            case R.id.kiss_layout:
                kiss_photo();
                break;
            case R.id.share:
                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                } else {
//                    String url = items.get(mViewPager.getCurrentItem()).getPhoto();
//                    mPopupWindow = PtThirdSharePopupWindow.Create(mActivity, url, PtThirdSharePopupWindow.SHARE_PHOTO);
//                    mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                    queryShare(v);
                }
                break;
            case R.id.btn_delete:
                showDeletePhotoDialog();
                break;
            case R.id.save:
                savePhoto();
                break;
            case R.id.tag_layout:
                showTagManagerDialog();
                break;
            case R.id.more_layout:
                showMoreDialog();
                break;
            default:
                break;

        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //Loger.d("chen+++onPageScrolled()++position=" + position);
    }

    @Override
    public void onPageSelected(int position) {
        //Loger.d("chen+++onPageSelected()++position=" + position);
        curPhotoPosition = position;
        upCurDateViewUi(fragments.get(position).getItem());

    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //Loger.d("chen+++onPageScrollStateChanged()++state=" + state);
    }

    private void showTagManagerDialog() {
        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        new PhotoTagManagerDialog
                .Builder(mContext)
                .setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setTagAddSuccessListener(new PhotoTagManagerDialog.TagAddListener() {
                    @Override
                    public void success(List<PtTag> tags) {
                        //updateTagUI(tags);
                        String tag = "标签";
                        if (tags.size() > 0) {
                            tag = "标签 " + tags.size();
                        }
                        tag_tv.setText(tag);
                    }
                })
                .Create(item.getPhoto_id())
                .show();
    }


//    private void updateTagUI(List<PtTag> tags) {
//        mTags.clear();
//        mTags.addAll(tags);
//        PtTag tag = new PtTag();
//        tag.setTitle(ADD_TAG_BTN_TEXT);
//        mTags.add(tag);
//        tag_view.setTags(mTags);

//    }

    /**
     * 更新 TAG 的UI
     *
     * @param item
     */
    private void updateTagUI(final PhotoViewItem item) {
        ArrayList<String> tagStrings = item.getTaglist();
//        List<PtTag> mTags = new ArrayList<PtTag>();
//        for (int i = 0; i < tagStrings.size(); i++) {
//            PtTag tag = new PtTag();
//            tag.setTitle(tagStrings.get(i));
//            mTags.add(tag);
//        }

        String tag = "标签";
        if (tagStrings.size() > 0) {
            tag = "标签 " + tagStrings.size();
        }

        tag_tv.setText(tag);
//        updateTagUI(mTags);
    }

    /**
     * 更新当前整个界面的UI
     *
     * @param item
     */

    public void upCurDateViewUi(int index, PhotoViewItem item) {
        if (index != curPhotoPosition) {
            return;
        }
        upCurDateViewUi(item);
    }


    public void upCurDateViewUi(PhotoViewItem item) {

        if (item == null) return;

        updateTagUI(item);

        if (item.getIs_choiceness() > 0) {
            colletion.setSelected(true);
        } else {
            colletion.setSelected(false);
        }

        int kissNum = StringHelper.stringToInt(item.getPraiseNums());
        if (kissNum > 0) {
            tips_kiss.setSelected(true);
            kiss_num.setText("亲 " + kissNum);
        } else {
            tips_kiss.setSelected(false);
            kiss_num.setText("亲一下");
        }

//        relation.setText("by " + item.getCreate_user());
    }


    /**
     * 亲的动画~~
     */
    private void startKissAnimation() {
        Animation scaleAnimation = new ScaleAnimation(1.0f, 0.2f, 1.0f, 0.2f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(100);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Animation scaleAnimation = new ScaleAnimation(0.2f, 1.2f, 0.2f, 1.2f,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                scaleAnimation.setDuration(100);
                tips_kiss.startAnimation(scaleAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        tips_kiss.startAnimation(scaleAnimation);

        startNewKissAnimation();
    }

    private void startNewKissAnimation() {
        //30%--0.1秒--50%--0.12秒--66%--0.12秒--50%--0.12秒---54%---0.2秒--52%--持续0.5秒--50%--0.2--%30消失
        //45%--0.1秒--75%--0.12秒--100%--0.12秒--75%--0.12秒---81%---0.2秒--78%--持续0.5秒--75%--0.2--%45消失

        Animation a = startNewKissAnimation(0.75f, 0.45f, 0.75f, 0.45f, 200, null);

        Animation b = startNewKissAnimation(0.78f, 0.75f, 0.78f, 0.75f, 500, a);

        Animation c = startNewKissAnimation(0.81f, 0.78f, 0.81f, 0.78f, 200, b);

        Animation d = startNewKissAnimation(0.75f, 0.81f, 0.75f, 0.81f, 120, c);

        Animation e = startNewKissAnimation(1.0f, 0.75f, 1.0f, 0.75f, 120, d);

        Animation f = startNewKissAnimation(0.75f, 1.0f, 0.75f, 1.0f, 120, e);

        Animation g = startNewKissAnimation(0.45f, 0.75f, 0.45f, 0.75f, 100, f);

        kiss_effect.setVisibility(View.VISIBLE);
        kiss_effect.startAnimation(g);
    }

    private Animation startNewKissAnimation(float fromX, float toX, float fromY, float toY, long durationMillis, final Animation endAnimation) {
        Animation scaleAnimation = new ScaleAnimation(fromX, toX, fromY, toY,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(durationMillis);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (endAnimation != null) {
                    kiss_effect.startAnimation(endAnimation);
                } else {
                    kiss_effect.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        return scaleAnimation;
    }


    /**
     * 亲照片
     */
    private void kiss_photo() {
        MobclickAgent.onEvent(mContext, UmengTouchEvent.KISS_PHOTO);
        final PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", item.getPhoto_id());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_PHOTO_PRAISE,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                //{"msg":"操作成功","data":{"praiseNums":"1"},"status":200}
                                String data = HttpRequestUtil.getResponseData(response).toString();
                                json = new JSONObject(data);
                                String praiseNums = json.getString("praiseNums");
                                item.setPraiseNums(praiseNums);
                                tips_kiss.setSelected(true);
                                kiss_num.setText("亲 " + praiseNums);
                            }
                            showToast(msg);
                            startKissAnimation();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                    }
                });
    }


    private void showDeletePhotoDialog() {
        new ConfirmDialogBuilder(mContext)
                .setMessage("真的需要删除照片吗？")
                .setPositiveButton(getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setNegativeButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deletePhoto();
                    }
                })
                .Create()
                .show();

    }

    private void deletePhoto() {
        final int position = mViewPager.getCurrentItem();
        final PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();

        final File tmp = DiskCacheUtils.findInCache(item.getPhoto(), ImageLoader.getInstance().getDiskCache());

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", item.getPhoto_id());
        params.put("baby_id", CommonUtils.getBabyId());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_PHOTO_DELETE,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                fragments.remove(position);
                                Bundle bundle = new Bundle();
                                if (fragments.size() < 1) {
                                    mActivity.finish();
                                    bundle.putBoolean("deleteAll", true);
                                } else {
                                    mFragmentAdapter.setmFragments(fragments);
                                    mViewPager.setAdapter(mFragmentAdapter);
                                    mViewPager.setCurrentItem(curPhotoPosition);
                                    mFragmentAdapter.notifyDataSetChanged();
                                    bundle.putBoolean("deleteAll", false);
                                }

                                String headHash = CommonUtils.getFileHeadHash(tmp);
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("babyId", CommonUtils.getBabyId());
                                map.put("headHash", headHash);
                                ArrayList<FileInfo> fileInfos = (ArrayList<FileInfo>) FileUploadDBHelper.getInstance().queryList(map);
                                if (fileInfos != null && fileInfos.size() > 0) {
                                    for (int i = 0; i < fileInfos.size(); i++) {
                                        FileInfo item = fileInfos.get(i);
                                        FileUploadDBHelper.getInstance().delete(item);
                                    }
                                }

                                try {
                                    tmp.delete();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                moreDialog.dismiss();
                                EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_PHOTO_DELETED, bundle));
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            showToast(getString(R.string.oprate_fail));
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        showToast(getString(R.string.oprate_fail));
                    }
                });

    }

    /**
     * 添加取消精选(收藏)
     */
    private void addCollection() {
        final int position = mViewPager.getCurrentItem();

        final PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", item.getPhoto_id());
        params.put("baby_id", CommonUtils.getBabyId());

        String url;
        if (item.getIs_choiceness() > 0) {
            url = PuTaoConstants.API_POST_PHOTO_DEL_CHOICENESS;
            MobclickAgent.onEvent(mContext, UmengTouchEvent.CANCEL_CHOICENESS);
        } else {
            url = PuTaoConstants.API_POST_PHOTO_ADD_CHOICENESS;
            MobclickAgent.onEvent(mContext, UmengTouchEvent.CHOICENESS);
        }

        HttpRequestUtil.doHttpPostRequest(mContext, url,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                if (item.getIs_choiceness() > 0) {
                                    item.setIs_choiceness(0);
                                    colletion.setSelected(false);
                                } else {
                                    item.setIs_choiceness(1);
                                    colletion.setSelected(true);
                                }
                                Bundle bundle = new Bundle();
                                EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_ADD_OR_REMOVE_COLLECTION, bundle));
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            showToast(getString(R.string.oprate_fail));
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        showToast(getString(R.string.oprate_fail));
                    }
                });

    }

    private void savePhoto() {
        int position = mViewPager.getCurrentItem();
        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        final File tmp = DiskCacheUtils.findInCache(item.getPhoto(), ImageLoader.getInstance().getDiscCache());
        if (tmp == null) {
            showToast("正在加载,请稍等...");
            return;
        }

        final File mediaFile = CommonUtils.getOutputMediaFile();

        CommonUtils.fileChannelCopy(tmp, mediaFile);
        final String[] SCAN_TYPES = {"image/jpeg"};
        MediaScannerConnection.scanFile(mContext, new String[]{mediaFile.getPath()}, SCAN_TYPES, null);
        showToast(getString(R.string.save_finish));
    }


    private void showMoreDialog() {
        moreDialog = new MoreDialog(mContext, R.style.pt_dialog_style);

        moreDialog.show();
    }

    private void selectBirthday() {
        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        int year, month, day;
        final Calendar c = new GregorianCalendar();
        c.setTimeInMillis(item.getShoot_time() * 1000L);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        Dialog dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            boolean seted;

            public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                Date date = new Date(new GregorianCalendar(year, month, dayOfMonth).getTimeInMillis());
                c.set(year, month, dayOfMonth);
                String time = new SimpleDateFormat(getString(R.string.time_format_ymd_hms)).format(new Date(c.getTimeInMillis()));
                if (!seted) {
                    modifytDate(time);
                    seted = true;
                }
            }
        }, year, // 传入年份
                month, // 传入月份
                day// 传入天数
        );
        dialog.show();
    }

    private void modifytDate(String date) {
        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", item.getPhoto_id());
        params.put("shoot_time", date);
        params.put("baby_id", CommonUtils.getBabyId());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_MODIFY_PHOTO_TIME,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                //{"msg":"操作成功","status":200}
                                moreDialog.dismiss();
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                    }
                });
    }

    private void report() {

        PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", item.getPhoto_id());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_PHOTO_REPORT,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {

                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            String msg = json.getString("msg");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                //{"msg":"操作成功","status":200}
                                moreDialog.dismiss();
                            }
                            showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                    }
                });
    }

    public class MoreDialog extends Dialog implements View.OnClickListener {
        private ShareTools mShareTools;
        private String mPhotoUrl, mAge;

        public MoreDialog(Context context, int theme) {
            super(context, theme);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            setContentView(getLayoutInflater().inflate(R.layout.dialog_photo_detail_more_layout, null));

            getWindow().setBackgroundDrawableResource(R.color.transparent);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(params);
            getWindow().setGravity(Gravity.BOTTOM);

            doInitListener();

            queryShare();
        }

        private void doInitListener() {
            findViewById(R.id.share_wechat_friend_ll).setOnClickListener(this);
            findViewById(R.id.share_wechat_ll).setOnClickListener(this);
            findViewById(R.id.share_qq_zone_ll).setOnClickListener(this);
            findViewById(R.id.share_weibo_ll).setOnClickListener(this);

            findViewById(R.id.save_layout).setOnClickListener(this);
            findViewById(R.id.modify_date_layout).setOnClickListener(this);
            findViewById(R.id.delete_layout).setOnClickListener(this);
            findViewById(R.id.report_layout).setOnClickListener(this);

            findViewById(R.id.cancle_btn).setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.share_wechat_friend_ll:
                    if (CommonUtils.isAppInstalled(mContext, "com.tencent.mm")) {
                        mShareTools.sendBitmapToWeixin(false);
                    } else {
                        Toast.makeText(mContext, "未安装微信", Toast.LENGTH_SHORT).show();
                    }
                    moreDialog.dismiss();
                    break;
                case R.id.share_wechat_ll:
                    if (CommonUtils.isAppInstalled(mContext, "com.tencent.mm")) {
                        mShareTools.sendBitmapToWeixin(true);
                    } else {
                        Toast.makeText(mContext, "未安装微信", Toast.LENGTH_SHORT).show();
                    }
                    moreDialog.dismiss();
                    break;
                case R.id.share_qq_zone_ll:
                    if (CommonUtils.isAppInstalled(mContext, "com.tencent.mobileqq")) {
                        mShareTools.doShareToQzone();
                    } else {
                        Toast.makeText(mContext, "未安装QQ", Toast.LENGTH_SHORT).show();
                    }
                    moreDialog.dismiss();
                    break;
                case R.id.share_weibo_ll:
                    if (CommonUtils.isAppInstalled(mContext, "com.sina.weibo")) {
                        mShareTools.doShareToWeibo();
                    } else {
                        Toast.makeText(mContext, "未安装新浪微博", Toast.LENGTH_SHORT).show();
                    }
                    moreDialog.dismiss();
                    break;
                case R.id.save_layout:
                    savePhoto();
                    moreDialog.dismiss();
                    break;
                case R.id.modify_date_layout:
                    selectBirthday();
                    break;
                case R.id.delete_layout:
                    showDeletePhotoDialog();
                    break;
                case R.id.report_layout:
                    report();
                    break;
                case R.id.cancle_btn:
                    dismiss();
                    break;
                default:
                    break;
            }

        }


        public void queryShare() {
            PhotoViewItem item = fragments.get(mViewPager.getCurrentItem()).getItem();
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("baby_id", CommonUtils.getBabyId());

            params.put("photo_id", item.getPhoto_id());

            mPhotoUrl = item.getPhoto();

            HttpRequestUtil.doHttpGetRequest(mActivity, PuTaoConstants.API_GET_SHARE_CONTENT,
                    new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                    new HttpRequestUtil.RequestResponseListener() {
                        @Override
                        public void success(int statuscode, String response) {
                            try {
                                JSONObject json = new JSONObject(response);
                                JSONObject data = json.getJSONObject("data");
                                String title = data.getString("title");

                                mShareTools = new ShareTools(mActivity, mPhotoUrl, title);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void failed(int statuscode, String response) {
                            Loger.d("response:::" + response);
                        }
                    });
        }

    }

}
